package com.niguang.work.api.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.niguang.common.constant.ResultCode;
import com.niguang.common.pojo.Result;
import com.niguang.common.util.ApiTokenUtils;
import com.niguang.common.util.ListPageUtil;
import com.niguang.work.api.constant.ApiDicConstants;
import com.niguang.work.api.entity.*;
import com.niguang.work.api.enums.*;
import com.niguang.work.api.mapper.ReformContentMapper;
import com.niguang.work.api.service.*;
import com.niguang.work.api.vo.ApplyListVo;
import com.niguang.work.api.vo.ZhengGaiTitleVo;
import com.niguang.work.api.weChatTemplate.service.ZhengGaiWeChatService;
import com.niguang.work.api.weChatTemplate.vo.ZhengGaiCcVo;
import com.niguang.work.api.weChatTemplate.vo.ZhengGaiPersonVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>
 * 'work.v_personSite' is not BASE TABLE 服务实现类
 * </p>
 *
 * @author 12380
 * @since 2018-09-06
 */
@Service
@Slf4j
public class ReformContentServiceImpl extends ServiceImpl<ReformContentMapper, ReformContent> implements ReformContentService {

    @Resource
    private ApiTokenUtils apiTokenUtils;

    @Resource
    private WechatUserService wechatUserService;

    @Resource
    private ReformUserService reformUserService;

    @Resource
    private QiyeSiteService qiyeSiteService;

    @Resource
    private ZhengGaiWeChatService zhengGaiWeChatService;

    @Resource
    private ReformApplyService reformApplyService;


    /**
     * 工人--个人列表
     */
    final static Map<Integer, String> personMap = new LinkedHashMap() {
        {
            put(1, ApiDicConstants.ZhengGaiTitle.OW_TI_JIAO_KEY);
            // put(2, ApiDicConstants.ZhengGaiTitle.SHANG_BAO_YIN_HUAN_KEY);
            // put(3, ApiDicConstants.ZhengGaiTitle.JI_FEN_JIANG_LI_KEY);

        }
    };


    /**
     * 整改--个人列表
     */
    final static Map<Integer, String> zhengGaiMap = new LinkedHashMap() {
        {
            put(1, ApiDicConstants.ZhengGaiTitle.OW_TI_JIAO_KEY);
            put(2, ApiDicConstants.ZhengGaiTitle.QUAN_BU_ZHENG_GAI_KEY);
            put(3, ApiDicConstants.ZhengGaiTitle.DAI_WO_ZHENG_GAI_KEY);
            put(4, ApiDicConstants.ZhengGaiTitle.DAI_WO_FU_CHA_KEY);
        }
    };


    /**
     * 审核--个人列表
     */
    final static Map<Integer, String> applyMap = new LinkedHashMap() {
        {
            put(1, ApiDicConstants.ZhengGaiTitle.OW_TI_JIAO_KEY);
            put(2, ApiDicConstants.ZhengGaiTitle.QUAN_BU_ZHENG_GAI_KEY);
            put(3, ApiDicConstants.ZhengGaiTitle.DAI_WO_FU_CHA_KEY);
            put(4, ApiDicConstants.ZhengGaiTitle.QUAN_BU_YIN_HUAN_KEY);
            put(5, ApiDicConstants.ZhengGaiTitle.DAI_WO_SHEN_HE_KEY);
        }
    };


    final static String JOB_POSITION = "工人";

    @Override
    public Result addReformContent(ReformContent reformContent) {
        String unionId = apiTokenUtils.getUnionId();
        WechatUser wechatUser = getWechatUser(unionId);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.FORBIDDEN, "微信号未绑定汇匠源平台，不允许提交~");
        }
        QiyeSite qiyeSite = qiyeSiteService.selectById(reformContent.getSiteId());
        if (ObjectUtils.isEmpty(qiyeSite)) {
            return Result.build(ResultCode.FORBIDDEN, "工地编号[" + reformContent.getSiteId() + "]不存在，请检查~");
        }
        EntityWrapper<ReformUser> reformUserEntityWrapper = new EntityWrapper<>();
        reformUserEntityWrapper.eq(ReformUser.UNION_ID, unionId).eq(ReformUser.SITE_ID, reformContent.getSiteId());
        ReformUser reformUser = reformUserService.selectOne(reformUserEntityWrapper);
        reformContent.setSiteName(qiyeSite.getSiteName());
        BeanUtils.copyProperties(wechatUser, reformContent);
        reformContent.setId(null);
        reformContent.setUnionId(unionId);
        reformContent.setCreateTime(null);
        if (ObjectUtils.isEmpty(reformUser)) {
            // 用户不是审核人
            reformContent.setJobPosition(JOB_POSITION);
        } else {
            reformContent.setJobPosition(reformUser.getJobPosition());
        }
        Integer insert = baseMapper.insert(reformContent);
        return Result.build(insert > 0 ? ResultCode.SUCCESS : ResultCode.FAILED, insert > 0 ? "上报隐患成功！" : "上报隐患失败，请稍后重试~");
    }

    @Override
    public Result getMyReformContent(Long siteId, Integer formFlag, Page<ReformContent> page) {
        String unionId = apiTokenUtils.getUnionId();
        WechatUser wechatUser = getWechatUser(unionId);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.FORBIDDEN, "微信号未绑定汇匠源平台，不允许查看~");
        }
        page.setAsc(false);
        List<ReformContent> reformContentList = baseMapper.getMyReformContent(wechatUser.getOpenId(), siteId, formFlag, page);
        Map<String, Object> map = new HashMap<>(4);
        page.setRecords(reformContentList);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());
        return Result.build(ResultCode.SUCCESS, "个人提交工单查看成功~", map);
    }

    @Override
    public Result getTitle(Long siteId, Integer formFlag) {
        String unionId = apiTokenUtils.getUnionId();
        //Integer formFlag = apiTokenUtils.getFormFlag();
        List<List<ZhengGaiTitleVo>> resultList = new ArrayList<>();
        // 我提交的条数
        int woTiJiaoNum = 0;
        // 积分奖励
        int jiFenJiangLi = 0;
        // 工人
        EntityWrapper<ReformContent> contentEntityWrapper = new EntityWrapper<>();
        contentEntityWrapper.eq(ReformContent.UNION_ID, unionId).eq(ReformContent.FORM_FLAG, formFlag).eq(ReformContent.SITE_ID, siteId);
        List<ReformContent> reformContentList = baseMapper.selectList(contentEntityWrapper);
        if (CollectionUtils.isNotEmpty(reformContentList)) {
            woTiJiaoNum = reformContentList.size();
            jiFenJiangLi = reformContentList.parallelStream().mapToInt(ReformContent::getIntegral).sum();
        }
        Map<String, Integer> map = new HashMap<>(7);
        map.put(ApiDicConstants.ZhengGaiTitle.OW_TI_JIAO_KEY, woTiJiaoNum);
        map.put(ApiDicConstants.ZhengGaiTitle.JI_FEN_JIANG_LI_KEY, jiFenJiangLi);
        EntityWrapper<ReformUser> reformUserEntityWrapper = new EntityWrapper<>();
        reformUserEntityWrapper.eq(ReformUser.UNION_ID, unionId).eq(ReformUser.SITE_ID, siteId);
        ReformUser reformUser = reformUserService.selectOne(reformUserEntityWrapper);
        WechatUser wechatUser = getWechatUser(unionId);
        if (!ObjectUtils.isEmpty(reformUser) && !ObjectUtils.isEmpty(wechatUser)) {
            // 整改
            int quanBuZhengGai = 0;
            int daiWoZhengGai = 0;
            int daiWoFuCha = 0;
            List<ReformContent> applyList = baseMapper.getApplyList(siteId, formFlag, null, null);
            if (CollectionUtils.isNotEmpty(applyList)) {

                quanBuZhengGai = (int) applyList.parallelStream().filter(p -> ContentApplyFlagEnum.WAIT_REFORM.getIndex().equals(p.getApplyFlag())
                        || ContentApplyFlagEnum.WAIT_REVIEW.getIndex().equals(p.getApplyFlag()) || ContentApplyFlagEnum.OK_APPLY.getIndex().equals(p.getApplyFlag())).count();

                // applyList = applyList.parallelStream().filter(p -> StringUtils.equals(wechatUser.getOpenId(), p.getOpenId())).collect(Collectors.toList());
                applyList = baseMapper.getApplyList(siteId, formFlag, wechatUser.getOpenId(), null);

                daiWoZhengGai = (int) applyList.parallelStream().filter(p ->
                        ContentApplyFlagEnum.WAIT_REFORM.getIndex().equals(p.getApplyFlag())).count();
                daiWoFuCha = (int) applyList.parallelStream().filter(p ->
                        ContentApplyFlagEnum.WAIT_REVIEW.getIndex().equals(p.getApplyFlag())).count();
            }
            if (ReformRoleTypeEnum.APPLY_USER.getIndex().equals(reformUser.getRoleType())) {
                // 审核人列表
                int daiWoShenHe = 0;
                int quanBuYinHuan = 0;
                EntityWrapper<ReformContent> reformContentEntityWrapper1 = new EntityWrapper<>();
                reformContentEntityWrapper1.in(ReformContent.APPLY_FLAG, ContentApplyFlagEnum.NOT_REFORM.getIndex() + ","
                        + ContentApplyFlagEnum.WAIT_REFORM.getIndex())
                        .or(ReformContent.ENABLE_FLAG + "=" + EnableFlagEnum.OK_FLAG.getIndex());

                List<ReformContent> reformContentList2 = baseMapper.selectList(reformContentEntityWrapper1);
                List<ReformContent> reformContentList1 = reformContentList2.parallelStream().filter(p -> p.getFormFlag().equals(formFlag) && p.getSiteId().equals(siteId)).collect(Collectors.toList());
                quanBuYinHuan = reformContentList1.size();
                daiWoShenHe = (int) reformContentList1.parallelStream().filter(p -> EnableFlagEnum.OK_FLAG.getIndex().equals(p.getEnableFlag())).count();
                map.put(ApiDicConstants.ZhengGaiTitle.QUAN_BU_ZHENG_GAI_KEY, quanBuZhengGai);
                map.put(ApiDicConstants.ZhengGaiTitle.DAI_WO_SHEN_HE_KEY, daiWoShenHe);
                map.put(ApiDicConstants.ZhengGaiTitle.QUAN_BU_YIN_HUAN_KEY, quanBuYinHuan);
                map.put(ApiDicConstants.ZhengGaiTitle.DAI_WO_FU_CHA_KEY, daiWoFuCha);
                resultList.add(buildTitle(applyMap, map));
            } else if (ReformRoleTypeEnum.REFORM_USER.getIndex().equals(reformUser.getRoleType())) {
                map.put(ApiDicConstants.ZhengGaiTitle.QUAN_BU_ZHENG_GAI_KEY, quanBuZhengGai);
                map.put(ApiDicConstants.ZhengGaiTitle.DAI_WO_ZHENG_GAI_KEY, daiWoZhengGai);
                map.put(ApiDicConstants.ZhengGaiTitle.DAI_WO_FU_CHA_KEY, daiWoFuCha);
                resultList.add(buildTitle(zhengGaiMap, map));
            }else {
                resultList.add(buildTitle(personMap, map));
            }
        } else {
            resultList.add(buildTitle(personMap, map));
        }
        return Result.build(ResultCode.SUCCESS, "标题查询成功~", resultList);
    }


    private List<ZhengGaiTitleVo> buildTitle(Map<Integer, String> titleMap, Map<String, Integer> titleParamsMap) {
        List<ZhengGaiTitleVo> resultList = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : titleMap.entrySet()) {
            resultList.add(new ZhengGaiTitleVo(ZhengGaiTitleEnum.getPageIndex(entry.getValue()), ZhengGaiTitleEnum.getTitle(entry.getValue()),
                    titleParamsMap.get(entry.getValue()), ZhengGaiTitleEnum.getIconUrl(entry.getValue())));
        }
        return resultList;
    }

    @Override
    public Result getApplyList(Long siteId, Integer menuType, Integer formFlag, Integer applyFlag, String key, Page<ReformContent> page) {
        String unionId = apiTokenUtils.getUnionId();
        WechatUser wechatUser = getWechatUser(unionId);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.FORBIDDEN, "微信号未绑定汇匠源平台，不允许提交~");
        }
        // 当前操作人信息
        EntityWrapper<ReformUser> reformUserEntityWrapper = new EntityWrapper<>();
        reformUserEntityWrapper.eq(ReformUser.UNION_ID, unionId).eq(ReformUser.SITE_ID, siteId);
        ReformUser reformUser = reformUserService.selectOne(reformUserEntityWrapper);
        if (ObjectUtils.isEmpty(reformUser)) {
            return Result.build(ResultCode.FORBIDDEN, "用户无审核权限，不允许查询~");
        }
        if (!ReformRoleTypeEnum.APPLY_USER.getIndex().equals(reformUser.getRoleType()) && !ReformRoleTypeEnum.REFORM_USER.getIndex().equals(reformUser.getRoleType())) {
            return Result.build(ResultCode.FORBIDDEN, "用户[" + reformUser.getUserName() + "]无审核权限，不允许查询~");
        }
        List<ReformContent> applyList = null;
        if ((ZhengGaiTitleEnum.QUAN_BU_YIN_HUAN_KEY.getPageIndex().equals(menuType)
                || ZhengGaiTitleEnum.DAI_WO_SHEN_HE_KEY.getPageIndex().equals(menuType))
                || ZhengGaiTitleEnum.QUAN_BU_ZHENG_GAI_KEY.equals(menuType)) {
            applyList = baseMapper.getApplyList(siteId, formFlag, null, key);
        } else {
            applyList = baseMapper.getApplyList(siteId, formFlag, wechatUser.getOpenId(), key);
        }

        List<ReformContent> collect = applyList.stream().filter(p -> p.getApplyFlag().equals(applyFlag)).collect(Collectors.toList());
        ListPageUtil<ReformContent> pageUtil = new ListPageUtil<>(collect, page.getCurrent(), page.getSize());
        Map<String, Object> map = new HashMap<>(4);
        map.put("total", pageUtil.getTotalCount());
        map.put("list", pageUtil.getPagedList());
        map.put("pages", pageUtil.getTotalPage());
        map.put("current", pageUtil.getNowPage());
        List<ApplyListVo.TitleVo> titleVoList = new ArrayList<>();
        if (ZhengGaiTitleEnum.QUAN_BU_YIN_HUAN_KEY.getPageIndex().equals(menuType) && ReformRoleTypeEnum.APPLY_USER.getIndex().equals(reformUser.getRoleType())) {
            // 待审核
            long waitApplyNum = applyList.stream().filter(p -> ContentApplyFlagEnum.WAIT_APPLY.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.WAIT_APPLY.getIndex(), waitApplyNum));
            // 需整改
            long needZhengGaiNum = applyList.stream().filter(p -> ContentApplyFlagEnum.WAIT_REFORM.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.WAIT_REFORM.getIndex(), needZhengGaiNum));
            // 不整改
            long notZhengGaiNum = applyList.stream().filter(p -> ContentApplyFlagEnum.NOT_REFORM.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.NOT_REFORM.getIndex(), notZhengGaiNum));

        } else if (ZhengGaiTitleEnum.QUAN_BU_ZHENG_GAI_KEY.getPageIndex().equals(menuType) || ReformRoleTypeEnum.REFORM_USER.getIndex().equals(reformUser.getRoleType())) {
            // 待整改
            long waitApplyNum = applyList.stream().filter(p -> ContentApplyFlagEnum.WAIT_REFORM.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.WAIT_REFORM.getIndex(), waitApplyNum));
            // 待复查
            long needZhengGaiNum = applyList.stream().filter(p -> ContentApplyFlagEnum.WAIT_REVIEW.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.WAIT_REVIEW.getIndex(), needZhengGaiNum));
            // 已完成
            long notZhengGaiNum = applyList.stream().filter(p -> ContentApplyFlagEnum.OK_APPLY.getIndex().equals(p.getApplyFlag())).count();
            titleVoList.add(new ApplyListVo.TitleVo(ContentApplyFlagEnum.OK_APPLY.getIndex(), notZhengGaiNum));
        }
        return Result.build(ResultCode.SUCCESS, "审核列表查询成功~", new ApplyListVo(titleVoList, map));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addReformApply(ReformApply reformApply) {
        String unionId = apiTokenUtils.getUnionId();
        Integer formFlag = apiTokenUtils.getFormFlag();
        reformApply.setFormFlag(formFlag);
        WechatUser wechatUser = getWechatUser(unionId);
        if (ObjectUtils.isEmpty(wechatUser)) {
            return Result.build(ResultCode.FORBIDDEN, "微信号未绑定汇匠源平台，不允许操作~");
        }
        ReformContent reformContent = baseMapper.selectById(reformApply.getContentId());
        if (ObjectUtils.isEmpty(reformApply)) {
            return Result.build(ResultCode.FORBIDDEN, "countId[" + reformApply.getContentId() + "]不存在！");
        }

        // 当前操作人信息
        EntityWrapper<ReformUser> reformUserEntityWrapper = new EntityWrapper<>();
        reformUserEntityWrapper.eq(ReformUser.UNION_ID, unionId).eq(ReformUser.SITE_ID, reformContent.getSiteId());
        ReformUser reformUser = reformUserService.selectOne(reformUserEntityWrapper);
        if (ObjectUtils.isEmpty(reformUser)) {
            return Result.build(ResultCode.FORBIDDEN, "用户无权限，不可操作~");
        }
        if (ApplyNodeStepEnum.APPLY_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 审核人操作节点。判断当前操作人是否是审核人
            if (!ReformRoleTypeEnum.APPLY_USER.getIndex().equals(reformUser.getRoleType())) {
                return Result.build(ResultCode.FORBIDDEN, "您不是审核人，不能操作审核功能~");
            }
        } else if (!ApplyNodeStepEnum.ZHUAN_FA_NODE.getIndex().equals(reformApply.getNodeStep()) && !ApplyNodeStepEnum.ZHENG_GAI_NODE.getIndex().equals(reformApply.getNodeStep())
                && !ApplyNodeStepEnum.FU_CHA_NODE.getIndex().equals(reformApply.getNodeStep()) && !ApplyNodeStepEnum.ZHENG_GAI_BO_HUI_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 整改人、复查人操作节点。判断当前操作人是否是整改人、复查人
            if (!ReformRoleTypeEnum.REFORM_USER.getIndex().equals(reformUser.getRoleType())) {
                return Result.build(ResultCode.FORBIDDEN, "您不是整改(复查)人，不能操作整改(复查)功能~");
            }
        }
        ReformUser appointUser = new ReformUser();
        if (!ApplyNodeStepEnum.FU_CHA_NODE.getIndex().equals(reformApply.getNodeStep())
                && !RoleApplyFlagEnum.NOT_REFORM.getIndex().equals(reformApply.getApplyFlag())
                && !ApplyNodeStepEnum.ZHENG_GAI_BO_HUI_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 指派人信息
            EntityWrapper<ReformUser> appointUserEntityWrapper = new EntityWrapper<>();
            appointUserEntityWrapper.eq(ReformUser.OPEN_ID, reformApply.getAppointUserId());
            appointUser = reformUserService.selectOne(appointUserEntityWrapper);
            if (ObjectUtils.isEmpty(appointUser)) {
                return Result.build(ResultCode.FORBIDDEN, "指派人不存在或未绑定微信号，请在企业后台查看此用户信息~");
            }
        }
        String msg = "";
        try {
            if (ApplyNodeStepEnum.APPLY_NODE.getIndex().equals(reformApply.getNodeStep())) {
                // 生成整改单
                reformApply = new ReformApply(reformApply.getContentId(), reformUser.getOpenId(), reformUser.getUserName(),
                        reformUser.getUserPhone(), reformUser.getJobPosition(), reformApply.getDangerLevel(), reformApply.getIntegral(), reformApply.getReformTerm(),
                        reformApply.getAppointUserId(), appointUser.getUserName(), appointUser.getUserPhone(), appointUser.getJobPosition(), appointUser.getOpenId(),
                        reformApply.getCcUserName(), reformApply.getCcUserId(), reformApply.getNodeStep(), reformApply.getApplyFlag(), reformApply.getFormFlag());
                Map<Integer, String> addApplyMap = addApply(reformApply);
                if (addApplyMap.containsKey(-1)) {
                    return Result.build(ResultCode.FAILED, addApplyMap.get(-1));
                } else if (addApplyMap.containsKey(1)) {
                    msg = "生成整改单成功，但" + addApplyMap.get(1);
                } else {
                    msg = RoleApplyFlagEnum.NOT_REFORM.getIndex().equals(reformApply.getApplyFlag()) ? "整改单操作成功~" : "生成整改单成功~";
                }
                baseMapper.updateById(new ReformContent(reformApply.getContentId(), reformApply.getDangerLevel(), reformApply.getReformTerm()));
            } else if (ApplyNodeStepEnum.ZHUAN_FA_NODE.getIndex().equals(reformApply.getNodeStep()) || ApplyNodeStepEnum.ZHENG_GAI_BO_HUI_NODE.getIndex().equals(reformApply.getNodeStep())
                    || ApplyNodeStepEnum.ZHENG_GAI_NODE.getIndex().equals(reformApply.getNodeStep())) {
                // 整改人：提交、驳回、转发，复查人：转发
                reformApply = new ReformApply(reformApply.getId(), reformApply.getContentId(), reformUser.getOpenId(), reformUser.getUserId(), reformUser.getUserName(), reformUser.getUserPhone(),
                        reformUser.getJobPosition(), appointUser.getUserName(), appointUser.getUserPhone(), appointUser.getJobPosition(), appointUser.getOpenId(),
                        reformApply.getCcUserName(), reformApply.getCcUserId(), reformApply.getDangerPic(), reformApply.getDangerDesc(), reformApply.getNodeStep(),
                        reformApply.getNodeStep1(), reformApply.getFormFlag());
                Map<Integer, String> addReformMap = addReform(reformApply);
                if (addReformMap.containsKey(-1)) {
                    return Result.build(ResultCode.FAILED, addReformMap.get(-1));
                } else if (addReformMap.containsKey(1)) {
                    msg = "提交成功，但" + addReformMap.get(1);
                } else {
                    msg = "提交成功~";
                    if (ApplyNodeStepEnum.ZHUAN_FA_NODE.getIndex().equals(reformApply.getNodeStep())) {
                        msg = "转发成功~";
                    } else if (ApplyNodeStepEnum.ZHENG_GAI_BO_HUI_NODE.getIndex().equals(reformApply.getNodeStep())) {
                        msg = "驳回成功~";
                    }
                }
            } else if (ApplyNodeStepEnum.FU_CHA_NODE.getIndex().equals(reformApply.getNodeStep())) {
                // 复查人
                reformApply = new ReformApply(reformApply.getId(), reformApply.getContentId(), reformUser.getOpenId(), reformUser.getUserName(),
                        reformUser.getUserPhone(), reformUser.getJobPosition(), reformApply.getCcUserName(), reformApply.getCcUserId(), reformApply.getDangerPic(),
                        reformApply.getDangerDesc(), reformApply.getNodeStep(), reformApply.getApplyFlag(), reformApply.getFormFlag());
                Map<Integer, String> addReformMap = addReview(reformApply);
                msg = "提交成功~";
                if (addReformMap.containsKey(-1)) {
                    return Result.build(ResultCode.FAILED, addReformMap.get(-1));
                } else if (addReformMap.containsKey(1)) {
                    msg = "提交成功，但" + addReformMap.get(1);
                }
            } else {
                return Result.build(ResultCode.FORBIDDEN, "操作节点【" + reformApply.getNodeStep() + "】类型错误~");
            }
        } catch (Exception e) {
            log.error("审核、整改、复查人操作异常：{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.success(msg);
    }

    /**
     * 审核人操作
     *
     * @param reformApply
     * @return
     */
    private Map<Integer, String> addApply(ReformApply reformApply) {
        Map<Integer, String> resultMap = new HashMap<>(1);
        if (reformApply.getApplyFlag() == null || reformApply.getApplyFlag() == 0) {
            resultMap.put(-1, "审核状态不能为空!");
            return resultMap;
        }
        if (RoleApplyFlagEnum.WAIT_REFORM.getIndex().equals(reformApply.getApplyFlag())) {
            // 待整改（需整改）
            if (reformApply.getAppointUserId() == null) {
                resultMap.put(-1, "指定整改人不能为空!");
                return resultMap;
            }
            if (ObjectUtils.isEmpty(reformApply.getDangerLevel())) {
                resultMap.put(-1, "隐患级别不能为空~");
                return resultMap;
            }
            if (StringUtils.isBlank(reformApply.getReformTerm())) {
                resultMap.put(-1, "整改期限不能为空~");
                return resultMap;
            }
            if (StringUtils.isNotBlank(reformApply.getCcUserId()) && StringUtils.isBlank(reformApply.getCcUserName())) {
                resultMap.put(-1, "抄送人[ccUserName]不能为空~");
                return resultMap;
            }
        }
        reformApply.setDealFlag(1);
        if (reformApplyService.insert(reformApply)) {
            // 修改主表用户增加积分及审核状态
            Integer applyFlag = RoleApplyFlagEnum.NOT_REFORM.getIndex().equals(reformApply.getApplyFlag()) ?
                    ContentApplyFlagEnum.NOT_REFORM.getIndex() : ContentApplyFlagEnum.WAIT_REFORM.getIndex();
            boolean updateById = this.updateById(new ReformContent(reformApply.getContentId(), reformApply.getIntegral(), applyFlag, EnableFlagEnum.NOT_FLAG.getIndex()));
            if (updateById && RoleApplyFlagEnum.WAIT_REFORM.getIndex().equals(reformApply.getApplyFlag())) {
                reformApply.setNodeStep(ApplyNodeStepEnum.ZHENG_GAI_NODE.getIndex());
                insertReformApply(reformApply);
                log.info("审核人操作生成整改单，微信通知处理");
                String result = sendWeChatNotice(reformApply);
                if (StringUtils.isNotBlank(result)) {
                    resultMap.put(1, result);
                }
            }
        }
        return resultMap;
    }

    /**
     * 整改人操作
     *
     * @param reformApply
     * @return
     */
    private Map<Integer, String> addReform(ReformApply reformApply) {
        Map<Integer, String> resultMap = new HashMap<>(1);
        if (reformApply.getId() == null) {
            resultMap.put(-1, "整改操作表单id不能为空!");
            return resultMap;
        }
        EntityWrapper<ReformApply> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.eq(ReformApply.CONTENT_ID, reformApply.getContentId()).eq(ReformApply.NODE_STEP, ApplyNodeStepEnum.APPLY_NODE.getIndex())
                .eq(ReformApply.DEAL_FLAG, 1).eq(ReformApply.VALID_FLAG, 0);
        ReformApply reformApply1 = reformApplyService.selectOne(entityWrapper1);
        if (ApplyNodeStepEnum.ZHENG_GAI_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 整改处理（提交）
            if (StringUtils.isBlank(reformApply.getDangerPic())) {
                resultMap.put(-1, "整改图片不能为空!");
                return resultMap;
            }
            if (StringUtils.isBlank(reformApply.getDangerDesc())) {
                resultMap.put(-1, "整改说明不能为空!");
                return resultMap;
            }
            if (reformApply.getAppointUserId() == null) {
                resultMap.put(-1, "指定复查人不能为空!");
                return resultMap;
            }
            reformApply.setNodeStep(ApplyNodeStepEnum.FU_CHA_NODE.getIndex());
            reformApply.setDangerLevel(reformApply1.getDangerLevel());
            reformApply.setReformTerm(reformApply1.getReformTerm());
            if (insertReformApply(reformApply)) {
                updateReformApply(reformApply);
                updateRefomContentApplyFlag(reformApply.getContentId(), ContentApplyFlagEnum.WAIT_REVIEW.getIndex());
                log.info("整改人操作提交工单到复查人，微信通知处理");
                String result = sendWeChatNotice(reformApply);
                if (StringUtils.isNotBlank(result)) {
                    resultMap.put(1, result);
                }
            }
        } else if (ApplyNodeStepEnum.ZHENG_GAI_BO_HUI_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 整改驳回
            reformApply.setValidFlag(1);
            reformApply.setDealFlag(1);
            if (updateReformApply1(reformApply)) {
                baseMapper.updateById(new ReformContent(reformApply.getContentId(), 0,
                        ContentApplyFlagEnum.WAIT_APPLY.getIndex(), EnableFlagEnum.OK_FLAG.getIndex()));
                EntityWrapper<ReformApply> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq(ReformApply.CONTENT_ID, reformApply.getContentId());
                ReformApply reformApply2 = new ReformApply();
                reformApply2.setContentId(reformApply.getContentId());
                reformApply2.setValidFlag(1);
                reformApplyService.update(reformApply2, entityWrapper);
            }
        } else if (ApplyNodeStepEnum.ZHUAN_FA_NODE.getIndex().equals(reformApply.getNodeStep())) {
            // 整改、复查人转发
            Integer nodeStep1 = reformApply.getNodeStep1();
            Integer nodeStep = reformApply.getNodeStep();
            reformApply.setDangerLevel(reformApply1.getDangerLevel());
            reformApply.setReformTerm(reformApply1.getReformTerm());
            reformApply.setNodeStep(nodeStep1);
            insertReformApply(reformApply);
            reformApply.setNodeStep(nodeStep);
            updateReformApply1(reformApply);
        } else {
            resultMap.put(1, "操作节点[nodeStep]参数[" + reformApply.getNodeStep() + "]错误");
        }
        return resultMap;
    }

    /**
     * 复查人操作
     *
     * @param reformApply
     * @return
     */
    private Map<Integer, String> addReview(ReformApply reformApply) {
        Map<Integer, String> resultMap = new HashMap<>(1);
        if (reformApply.getId() == null) {
            resultMap.put(-1, "复查操作表单id不能为空!");
            return resultMap;
        }
        reformApply.setDealFlag(1);
        if (RoleApplyFlagEnum.OK_APPLY.getIndex().equals(reformApply.getApplyFlag())) {
            // 审核通过
            if (StringUtils.isBlank(reformApply.getDangerPic())) {
                resultMap.put(-1, "复查图片不能为空!");
                return resultMap;
            }
            if (StringUtils.isBlank(reformApply.getDangerDesc())) {
                resultMap.put(-1, "复查说明不能为空!");
                return resultMap;
            }
            if (updateReformApply(reformApply)) {
                updateRefomContentApplyFlag(reformApply.getContentId(), ContentApplyFlagEnum.OK_APPLY.getIndex());
            } else {
                resultMap.put(-1, "审核通过操作失败~");
                return resultMap;
            }
        } else {
            // 审核不通过
            EntityWrapper<ReformApply> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq(ReformApply.CONTENT_ID, reformApply.getContentId()).eq(ReformApply.NODE_STEP, ApplyNodeStepEnum.APPLY_NODE.getIndex())
                    .eq(ReformApply.DEAL_FLAG, 1).eq(ReformApply.VALID_FLAG, 0);
            ReformApply reformApply1 = reformApplyService.selectOne(entityWrapper);
            reformApply1.setNodeStep(ApplyNodeStepEnum.ZHENG_GAI_NODE.getIndex());
            reformApply.setAppointOpenId(reformApply1.getAppointOpenId());
            reformApply.setAppointJobPosition(reformApply1.getAppointJobPosition());
            reformApply.setAppointUserId(reformApply1.getAppointUserId());
            reformApply.setAppointUserName(reformApply1.getAppointUserName());
            reformApply.setAppointUserPhone(reformApply1.getAppointUserPhone());
            if (!(insertReformApply(reformApply1) && updateReformApply(reformApply))) {
                resultMap.put(-1, "审核不通过操作失败~");
                return resultMap;
            } else {
                updateRefomContentApplyFlag(reformApply.getContentId(), ContentApplyFlagEnum.WAIT_REFORM.getIndex());
            }
        }
        if (StringUtils.isNotBlank(reformApply.getCcUserId())) {
            log.info("复查人操作，微信通知处理");
            String result = sendWeChatNotice(reformApply);
            if (StringUtils.isNotBlank(result)) {
                resultMap.put(1, result);
            }
        }
        return resultMap;
    }


    private Integer updateRefomContentApplyFlag(Long contentId, Integer applyFlag) {
        return baseMapper.updateById(new ReformContent(contentId, applyFlag));
    }

    /**
     * 整改、复查修改
     *
     * @param reformApply
     * @return
     */
    private boolean updateReformApply(ReformApply reformApply) {
        reformApply = new ReformApply(reformApply.getId(), reformApply.getAppointUserName(), reformApply.getAppointUserPhone(),
                reformApply.getAppointJobPosition(), reformApply.getAppointOpenId(), reformApply.getCcUserName(), reformApply.getCcUserId(),
                reformApply.getDangerPic(), reformApply.getDangerDesc(), reformApply.getApplyFlag());
        return reformApplyService.updateById(reformApply);
    }


    /**
     * 转发处理、驳回
     *
     * @param reformApply
     * @return
     */
    private boolean updateReformApply1(ReformApply reformApply) {
        reformApply = new ReformApply(reformApply.getId(), reformApply.getAppointUserName(), reformApply.getAppointUserPhone(),
                reformApply.getAppointJobPosition(), reformApply.getAppointOpenId(), reformApply.getCcUserName(), reformApply.getCcUserId(),
                reformApply.getDangerPic(), reformApply.getDangerDesc(), reformApply.getApplyFlag(), reformApply.getNodeStep());
        return reformApplyService.updateById(reformApply);
    }


    /**
     * 整改、复查插入操作
     *
     * @param reformApply
     * @return
     */
    private boolean insertReformApply(ReformApply reformApply) {
        reformApply = new ReformApply(reformApply.getContentId(), reformApply.getAppointOpenId(), reformApply.getAppointUserName(),
                reformApply.getAppointUserPhone(), reformApply.getAppointJobPosition(), reformApply.getNodeStep(),
                reformApply.getDangerLevel(), reformApply.getReformTerm(), reformApply.getFormFlag());
        return reformApplyService.insert(reformApply);
    }


    /**
     * 发送微信通知：审核人、整改人、复查人
     *
     * @param reformApply
     * @return
     */
    private String sendWeChatNotice(ReformApply reformApply) {
        String resultMsg = "";
        if (StringUtils.isNotBlank(reformApply.getAppointOpenId())) {
            ReformContent reformContent1 = baseMapper.selectById(reformApply.getContentId());
            log.info("责任人：【{}】发送微信通知.....", reformApply.getAppointUserName());
            ReformContent reformContent = getReformContentById(reformApply.getContentId());
            ZhengGaiPersonVo zhengGaiPersonVo = new ZhengGaiPersonVo(reformApply.getAppointOpenId(), String.valueOf(reformApply.getContentId()),
                    FormFlagEnum.getName(reformContent.getFormFlag()), reformContent.getSiteName(),
                    reformContent.getDangerTitle(), DangerLevelEnum.getName(reformApply.getDangerLevel()), reformApply.getReformTerm(), reformContent1.getUserName(),
                    reformApply.getApplyUserName(), reformContent.getDangerDesc());
            if (!zhengGaiWeChatService.sendPerson(zhengGaiPersonVo)) {
                resultMsg = "责任人【" + reformApply.getAppointUserName() + "】微信通知失败；";
            }
        } else {
            if (!ApplyNodeStepEnum.FU_CHA_NODE.getIndex().equals(reformApply.getNodeStep())) {
                log.info("责任人：【{}】未获取到微信openId，发送微信通知失败", reformApply.getAppointUserName());
                resultMsg += "责任人【" + reformApply.getAppointUserName() + "】微信通知失败,原因：未获取到微信openId；";
            }
        }
        if (StringUtils.isNotBlank(reformApply.getCcUserId())) {
            // 抄送人不为空，发送微信消息通知
            List<String> list = new ArrayList<>();
            if (StringUtils.isNotBlank(reformApply.getCcUserId())) {
                list = Arrays.asList(reformApply.getCcUserId().split(","));
            }
            if (CollectionUtils.isNotEmpty(list)) {
                ReformContent reformContent = getReformContentById(reformApply.getContentId());
                log.info("抄送人：【{}】发送微信通知.....", reformApply.getCcUserName());
                AtomicBoolean ok = new AtomicBoolean(true);
                list.forEach(p -> {
                    ZhengGaiCcVo zhengGaiCcVo = new ZhengGaiCcVo(p, reformApply.getContentId(), FormFlagEnum.getName(reformContent.getFormFlag()),
                            reformContent.getSiteName(), reformContent.getDangerTitle(), DangerLevelEnum.getName(reformApply.getDangerLevel()),
                            RoleApplyFlagEnum.getName(reformContent.getApplyFlag()), reformContent.getDangerDesc(), reformApply.getReformTerm());
                    ok.set(zhengGaiWeChatService.sendCcWeChat(zhengGaiCcVo));
                });
                resultMsg += ok.get() ? "" : "抄送人微信通知失败；";
            } else {
                log.info("抄送微信通知openId为空,抄送人发送信息失败！");
                resultMsg += "抄送人微信通知失败,原因：未获取到微信openId；";
            }
        }
        return resultMsg;
    }


    private ReformContent getReformContentById(Long contentId) {
        return baseMapper.selectById(contentId);
    }


    /**
     * 获取用户openId
     *
     * @param userIds 89 or 123,569
     * @return
     */
    private List<String> getOpenIdByUserId(String userIds) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isBlank(userIds)) {
            return list;
        }
        EntityWrapper<WechatUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.in(WechatUser.USER_ID, userIds);
        List<WechatUser> wechatUsers = wechatUserService.selectList(entityWrapper);
        wechatUsers.forEach(p -> {
            if (StringUtils.isNotBlank(p.getOpenId())) {
                list.add(p.getOpenId());
            }
        });
        return list;
    }


    private WechatUser getWechatUser(String unionId) {
        EntityWrapper<WechatUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(WechatUser.UNION_ID, unionId);
        return wechatUserService.selectOne(entityWrapper);
    }

}
